var express = require('express');
var router = express.Router();
const WxApi =  require('../lib/wx.api')


// 查看access_token
router.get('/access_token', (req, res, next)=> {
	res.send(req.wx.accessToken)
})

// 查看jsapi_ticket
router.get('/jsapi_ticket', (req, res, next)=> {
    res.send(req.wx.jsapiTicket)
})

// 查看微信菜单
router.get('/menuinfo', (req, res, next)=> {
    WxApi.getMenuinfo(req.wx.accessToken)
        .then(menuinfo=> {
            res.render('wxmenu', {menuinfo: menuinfo})
        })
        .catch(err=> {
            res.send(err)
        })
})

// 创建微信菜单
router.post('/menucreate', async (req, res, next)=> {
    let data = {
        "button":[
            {    
                "type":"click",
                "name":"消息",
                "key":"V1001_TODAY_MUSIC"
            },
            {    
               "type":"view",
               "name":"微信sdk",
               "url":"http://sorry510.cn/wx/jssdk"
            },
            {
               "name":"小程序",
               "sub_button":[
                    {
                        "type":"miniprogram",
                        "name":"wxa",
                        "url":"http://mp.weixin.qq.com",
                        "appid":"wx286b93c14bbf93aa",
                        "pagepath":"pages/lunar/index"
                    },
                ]
            }
        ]
    }

    let result = await WxApi.setMenu(req.wx.accessToken, data)
    if(result) {
        res.send('success')
    }else {
        res.send('failed')
    }
})


// 用户同意授权微信重定向的统一入口获code，通过code获取临时的access_token
// REDIRECT_URI == encodeURIComponent('http://sorry510.cn/wx/oauth2?redirect=/wx/jssdk')
// scope 有两种 应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
// url 来源https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
router.get('/oauth2', (req, res, next)=> {
    let code = req.query.code
    let redirect = req.query.redirect || '/wx/jssdk'// 需要再次重定向的url
    WxApi.oauth2(code)
        .then(oauth2Info=> {
            req.session.oauth2 = oauth2Info
            // { "access_token":"ACCESS_TOKEN",
            // "expires_in":7200,
            // "refresh_token":"REFRESH_TOKEN",
            // "openid":"OPENID",
            // "scope":"SCOPE" }
            // todo save res
            return WxApi.getUserInfo(oauth2Info.access_token, oauth2Info.openid)
        })
        .then(userInfo=> {
            req.session.userInfo = userInfo
            res.redirect(redirect)
        })
        .catch(err => {
            console.log(err)
            res.send('oauth2认证失败')
        })
})

// jssdk首页
router.get('/jssdk', (req, res, next)=> {
    console.log(req.session)
    const url = req.protocol + '://' + req.hostname + req.originalUrl
    let wxConfig = WxApi.getJsSdkConfig(req.wx.jsapiTicket, url, ['chooseImage'])
	res.render('wxsdk', { wxConfig: wxConfig, appid: req.wx.config.appid })
})

// 图片接口页面
router.get('/img', (req, res, next)=> {
    const url = req.protocol + '://' + req.hostname + req.originalUrl
    let wxConfig = WxApi.getJsSdkConfig(req.wx.jsapiTicket, url)
    res.render('wximg', { wxConfig: wxConfig, wx: req.wx })
})

// 图片接口页面
router.get('/share', (req, res, next)=> {
    const url = req.protocol + '://' + req.hostname + req.originalUrl
    let wxConfig = WxApi.getJsSdkConfig(req.wx.jsapiTicket, url)
    res.render('wxshare', { wxConfig: wxConfig, wx: req.wx})
})

// 微信用户信息
router.get('/userinfo', (req, res, next)=> {
    const userInfo = req.session.userInfo || {}
    const url = req.protocol + '://' + req.hostname + req.originalUrl
    let wxConfig = WxApi.getJsSdkConfig(req.wx.jsapiTicket, url)
    res.render('wxuserinfo', { wxConfig: wxConfig, wx: req.wx, userInfo:userInfo })
})

module.exports = router
